package logic

import (
	"context"
	"fmt"
	"jd-mall/jd/cache"
	"jd-mall/jd/models"

	"jd-mall/jd/internal/svc"
	"jd-mall/jd/jd"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCarLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCarLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCarLogic {
	return &AddCarLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCarLogic) AddCar(in *jd.AddCarRequest) (*jd.AddCarResponse, error) {
	// todo: add your logic here and delete this line
	var g models.Goods
	var err error
	if err = g.GetGoodsCar(int(in.GoodsId)); err != nil {
		logx.Error("商品不存在")
		return nil, err
	}
	if g.Num < int(in.Num) {
		logx.Error("库存不足")
		return nil, err
	}
	if g.Num > 200 {
		logx.Error("超出商品库存")
		return nil, err
	}
	if cache.IsExisit(int(in.UserId), int(in.GoodsId)) {
		fmt.Println("购物车存在此商品")
		cache.UpdateCar(int(in.UserId), int(in.GoodsId), int(in.Num))
		logx.Error("累加失败")
	} else {
		goodsmap := map[string]interface{}{
			"title":   in.Title,
			"price":   in.Price,
			"num":     in.Num,
			"status":  1,
			"userId":  in.UserId,
			"goodsId": in.GoodsId,
		}
		if err = cache.AddCar(int(in.UserId), int(in.GoodsId), goodsmap); err != nil {
			logx.Error("添加失败")
		}
	}
	return &jd.AddCarResponse{
		GoodsId: in.GoodsId,
	}, nil
}
